package com.xiaoc.bulldozer.facade.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.xiaoc.bulldozer.common.Constant;
import com.xiaoc.bulldozer.common.SendMessageConstat;
import com.xiaoc.bulldozer.common.TemplateMessageConstant;
import com.xiaoc.bulldozer.common.WeixinConstant;
import com.xiaoc.bulldozer.common.dto.AccountQueryDto;
import com.xiaoc.bulldozer.common.dto.WeixinFormIdDto;
import com.xiaoc.bulldozer.common.model.Account;
import com.xiaoc.bulldozer.common.model.SendMessageLog;
import com.xiaoc.bulldozer.common.service.AccountService;
import com.xiaoc.bulldozer.common.service.SendMessageLogService;
import com.xiaoc.bulldozer.common.service.SmtpMessageService;
import com.xiaoc.bulldozer.common.service.WeixinFormIdService;
import com.xiaoc.bulldozer.facade.SendMessageFacade;
import com.xiaoc.bulldozer.service.WxService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service("sendMessageFacade")
public class SendMessageFacadeImpl implements SendMessageFacade {

    private Logger logger = LoggerFactory.getLogger(SendMessageFacadeImpl.class);

    @Resource(name = "smtpMessageService")
    private SmtpMessageService smtpMessageService;

    @Value("${wechat.miniapp.templateId}")
    private String templateId;

    @Resource(name = "weixinFormIdService")
    private WeixinFormIdService weixinFormIdService;

    @Resource(name = "wxService")
    private WxService wxService;

    @Resource
    private CloseableHttpClient closeableHttpClient;

    @Resource(name = "sendMessageLogService")
    private SendMessageLogService sendMessageLogService;

    @Resource(name = "accountService")
    private AccountService accountService;


    @Override
    public void sendWeixinMessage(Set<String> phoneNumberSet, String content1, String content2) {

        List<SendMessageLog> sendMessageLogList = new ArrayList<>();

        long current =System.currentTimeMillis();

        //通过手机号查询formId
        List<WeixinFormIdDto> weixinFormIdList = weixinFormIdService.getWeixinFormIdListByPhoneNumberSet(phoneNumberSet);

        if (CollectionUtils.isNotEmpty(weixinFormIdList)) {
            for (WeixinFormIdDto weixinFormIdDto : weixinFormIdList) {

                SendMessageLog sendMessageLog = new SendMessageLog();
                sendMessageLog.setStatus(Constant.ENABLE);
                sendMessageLog.setContent(content1.concat(content2));
                sendMessageLog.setReceiver(weixinFormIdDto.getPhoneNumber());
                sendMessageLog.setType(Integer.parseInt(SendMessageConstat.WEIXIN_MESSAGE));
                sendMessageLog.setCreateTime(current);
                JsonObject requestJson = null;
                try {


                    String accessToken = wxService.getAccessToken();

                    String url = WeixinConstant.SEND_TEMPLATE_MESSAGE_URL.concat(accessToken);

                    JSONObject params = messageData(weixinFormIdDto.getOpenId(), weixinFormIdDto.getFormId(), content1, content2);

                    requestJson = postJson(closeableHttpClient, url, params);

                    logger.info("sendWeixinMessage requestJson={}", requestJson);

                    sendMessageLog.setResult(requestJson.toString());

                } catch (Exception e) {
                    logger.error("sendWeixinMessage error", e.getMessage());

                    sendMessageLog.setStatus(Constant.DISABLE);
                    sendMessageLog.setResult(e.getMessage());

                } finally {

                    sendMessageLogList.add(sendMessageLog);
                }

            }


            sendMessageLogService.saveBatch(sendMessageLogList);

            weixinFormIdService.updateStatusBatch(weixinFormIdList, TemplateMessageConstant.STAUTS_SEND, current);

        }

    }

    @Override
    public void sendSMS(Set<String> phoneNumberSet, String content) {

        List<SendMessageLog> sendMessageLogList = new ArrayList<>();
        long current =System.currentTimeMillis();
        if (CollectionUtils.isNotEmpty(phoneNumberSet)) {
            for (String phoneNumber : phoneNumberSet) {

                SendMessageLog sendMessageLog = new SendMessageLog();
                sendMessageLog.setStatus(Constant.ENABLE);
                sendMessageLog.setContent(content);
                sendMessageLog.setReceiver(phoneNumber);
                sendMessageLog.setType(Integer.parseInt(SendMessageConstat.SMS));
                sendMessageLog.setCreateTime(current);
                try {

                    smtpMessageService.sendMessage(phoneNumber, content);
                    sendMessageLog.setResult("成功");

                } catch (Exception e) {
                    logger.error("sendSMS error", e.getMessage());
                    sendMessageLog.setResult(e.getMessage());

                } finally {

                    sendMessageLogList.add(sendMessageLog);
                }


            }
            
            sendMessageLogService.saveBatch(sendMessageLogList);
        }


    }

    @Override
    public void sendSMSByType(String type, String content) {


        AccountQueryDto accountQueryDto = new AccountQueryDto();

        List<Account> accountList = new ArrayList<>();

        //内部员工
        /*if (StringUtils.equals(type, SendMessageConstat.INNER)) {
            accountList = accountService.getAccountListByCondition(accountQueryDto);

        }else if (StringUtils.equals(type, SendMessageConstat.EXTERNAL_VALID)) {

            accountQueryDto.setType(Constant.ACCOUNT_TYPE.USER);

            accountList = accountService.getAccountListByCondition(accountQueryDto);

        }else if (StringUtils.equals(type, SendMessageConstat.INNER_AND_EXTERNAL_VALID)) {

            accountList = accountService.getAccountListByCondition(accountQueryDto);

            accountQueryDto = new AccountQueryDto();

            accountQueryDto.setType(Constant.ACCOUNT_TYPE.USER);

            List<Account> externalValidList = accountService.getAccountListByCondition(accountQueryDto);
            if (CollectionUtils.isNotEmpty(externalValidList)) {
                accountList.addAll(externalValidList);
            }


        }*/

        Set<String> phoneNumberSet = new TreeSet<>();
        for(Account account : accountList) {
            phoneNumberSet.add(account.getPhoneNumber());
        }

        this.sendSMS(phoneNumberSet, content);

    }

    private JsonObject postJson(CloseableHttpClient httpClient, String url, JSONObject json) {
        try {
            HttpPost httpPost = new HttpPost(url);

            StringEntity entity = new StringEntity(json.toString(), "utf-8");

            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");

            httpPost.setEntity(entity);

            CloseableHttpResponse response = httpClient.execute(httpPost);
            String content = EntityUtils.toString(response.getEntity(), "UTF-8");

            return (new JsonParser()).parse(content).getAsJsonObject();
        } catch (Exception e) {
            logger.error("获取接口失败", e);
            throw new RuntimeException(e);
        }
    }

    private JSONObject messageData(String openId, String formId, String content1, String content2) {
        JSONObject params = new JSONObject();
        params.put("touser", openId);
        params.put("template_id", templateId);
        params.put("page", "pages/index/index");
        params.put("form_id", formId);

        Map<String, JSONObject> dataMap = new HashMap<>();

        String[] keywords = {content1, content2};

        for (int i = 0; i < keywords.length; i++) {

            int keywordIndex = i + 1;
            JSONObject value = new JSONObject();
            value.put("value", keywords[i]);
            dataMap.put("keyword" + keywordIndex, value);
        }


        params.put("data", dataMap);
        params.put("emphasis_keyword", TemplateMessageConstant.EMPHASIS_KEYWORD);
        return params;
    }

}
